package com.basic.shiro.realms;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

public class SecondRealm extends AuthenticatingRealm {
    private Logger log = Logger.getLogger(SecondRealm.class);
    /*
     * 从ShiroHandler中的 currentUser.login(token)中传过来*/
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("secondRealm");
// *1.AuthenticationToken转回usernamePasswordAuthenticationToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//     * 2.从usernamePasswordAuthenticationToken中获取username和password
        String username = upToken.getUsername();
//     * 3.调用数据库方法从数据库中查询username用户对应的记录
    ;
        System.out.println("从数据库中获取username:" + username );
//     * 4.若用户不存在则可以抛出异常
        if (username.equals(" ")) {
            throw new UnknownAccountException("用户不存在");
        }
//     * 5.根据用户信息情况决定是否需要抛出其他异常，如账号被锁定
        if (username.equals("0")) {
            throw new LockedAccountException("账号被锁定");
        }
//     * 6.根据用户的情况构建AuthenticationInfo并返回*
        /*以下信息从数据库中获取的
        * 1.principal 认证的实体信息 可以是username 也可以是数据表对应的用户的实体类对象
        * 2.credentials :从数据库中获取的密码
        * 3.realmName :当前realm 对象的name 调用父类的getName()方法即可*/
        Object principal = username;
        Object credentials = null;
        if ("admin".equals(username)){
            credentials= "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
        }else if ("user".equals(username)){
            credentials= "073d4c3ae812935f23cb3f2a71943f49e082a718";
        }
        String realmName =getName();
//         盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("SecondRealm",credentials,credentialsSalt,realmName);
        return info;
    }

    public static void main(String[] args) {
        String hashAlgorithmName="SHA1";
        Object credentials = "123456";
        Object salt ="admin";
        int hashIterations =1024;
        Object result = new SimpleHash(hashAlgorithmName,credentials,salt,hashIterations);
        System.out.println(result);
    }
}
